<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Controller;
use think\Request;
use think\facade\Cache;
use wechat\Wechat;
use think\Db;
use app\api\controller\Mqtt;

class BatteryOrder extends Api
{
    public function index()
    {
        if($this->request->isPost())
        {
            $post = post();
            if(!isset($post['user_id'])) return fh(200,'error','缺少用户ID',[]);
            $list = ysh_select($this->request->controller(),['with'=>'battery.batteryba.business','where'=>[['user_id','=',$post['user_id']]]]);
            if(!empty($list)){
            	$time = time();
            	foreach($list['list']['data'] as $k=>$v){
	            	if($v['status'] == 1){
	            		$list['list']['data'][$k]['update_time'] = date('Y-m-d H:i:s',$time);
	            	}else{
	            		$list['list']['data'][$k]['update_time'] = date('Y-m-d H:i:s',$v['update_time']);
	            	}
	            	$list['list']['data'][$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
	            }
            }
            
            return fh(200,'success','',$list);
        }
    }
    public function add()
    {
        if($this->request->isPost())
        {
            $post = post();
            if(!isset($post['user_id'])) return fh(200,'error','缺少用户id',[]);
            if(!isset($post['id'])) return fh(200,'error','缺少机台id',[]);
            if(!isset($post['money_id'])) return fh(200,'error','缺少金额id',[]);
            if(!isset($post['code'])) return fh(200,'error','缺少code',[]);
            $code = $post['code'];
            //选择的金额
            $money = model('battery_money')->get($post['money_id'])->toArray();
            $time = time();
            //选择的机台
            $batteryba = model('batteryba')->get($post['id'])->toArray();
            if($batteryba['type'] == 1){
            	return fh(200,'error','正在使用中',[]);
            }
            if($code){
				$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->appsecret&js_code=$code&grant_type=authorization_code";
				$curl = curl_send(['url'=>$url]);
				if(strpos($curl['content'],'errcode')){
					return fh(200,'error','获取openid失败'.$curl['content'],[]);
				}
				if(strpos($curl['content'],'error')){
					return fh(200,'error','获取openid失败'.$curl['content'],[]);
				}
				$arr = json_decode($curl['content']);
				// unset($arr['session_key']);
				$openid = explode(':',str_replace('}','',str_replace('"','',explode(',',$curl['content'])[1])))[1];
    		}else{
    			return fh('404','error','缺少code',[]);
    		}
            $orderid = date('YmdHis').mt_rand(10000,99999);
        	$data = [
                'user_id'=>$post['user_id'],
                'status'=>1,
                'business_id'=>$batteryba['business_id'],
                'battery_id'=>$batteryba['id'],
                'time'=>$money['time'],
                'orderid'=>$orderid,
                'create_time'=>$time,
                'money_title'=>$money['title'] . $money['money'],
                'money'=>$money['money']
            ];
        	//添加订单
        	$upload = ysh_save($this->request->controller(),$data);
            if($upload){
            	$pay = $this->cecz(['name'=>'租赁充电宝','content'=>'租赁充电宝','orderid'=>$orderid],$openid);
            	return json_encode($pay,JSON_UNESCAPED_UNICODE);
                // return fh(200,'success','添加订单成功',$data);
            }else{
                return fh(200,'error','添加失败,数据存在问题',$upload);
            }
        }
    }
    
    public function cecz($order,$openid)
    {
        $wechat = Wechat::instance($this->appid,$this->appsecret);
        $wepay = $wechat->pay($this->mchid,$this->mchkey);
        $params = [
            'body'=>$order['name'],
            'detail'=>$order['content']?: '没有介绍',
            'out_trade_no'=>$order['orderid'],
            'total_fee'=>1000*100,
            // 'total_fee'=>2,
            'notify_url'=>url('api/user/notifyfwzx', [], '', true),
            'openid'=>$openid
        ];
        $result = $wepay->unifiedorder($params);
        if($result){
            return  json_decode(fh(200,'success','请求成功',$result));
        }else{
        	// return $wepay->getErrCode .':' .$wepay->getErrMsg();
            return fh(1,'error','失败',$wepay->getErrCode .':' .$wepay->getErrMsg());
        }
    }
    public function notifyfwzx()
    {
        $xml = file_get_contents("php://input");
        trace($xml);
        header("Content-Type: application/xml;");
        //var_dump($this->appsecret);
        $wechat = Wechat::instance($this->appid,$this->appsecret);
        $payModel = $wechat->pay($this->mchid,$this->mchkey);
        //签名验证并返回订单信息
        $wxOrder = $payModel->notify();
        if (!empty($wxOrder)) {
            if (strtolower($wxOrder['return_code']) == 'success') {
                //取得系统订单
                $order = Order::getByOrderid($wxOrder['out_trade_no']);
                if (empty($order)) {
                    trace("订单未找到，订单号：{$wxOrder['out_trade_no']}\n" . var_export($wxOrder, true), 'wechat');
                } else {
                	$name = $order['name'];
                	$orderid = $order['orderid'];
                	$mqtt = new Mqtt($this->server, $this->port, '133'); //实例化MQTT类
			        //机台信息
			        $jt = model('batteryba')->where('batterybaid','=',$name)->find()->toArray();
			        //充电结束时间
			        $time = $order['time']*60+time();
            		ysh_upload('batteryba',['id'=>$jt['id'],'type'=>1,'de_time'=>date('Y-m-d H:i:s',$time)]);
            		$ordermoney = $order['money'];
            		$c_time = date('Y-m-d H:i:s',$order['create_time']);
            		$cdtime = $order['cd_time']*1*60;
			        if ($mqtt->connect(true, NULL, $this->username, $password)) {
			            //如果创建链接成功
			            $mqtt->publish('baosheng/pay/notift/' . $name, "{
			            	'status':'success',
			            	'code':200,
			            	'message':'支付成功',
			            	'orderid':$orderid,
			            	'end_time':$time
			            	'money':$ordermoney,
			            	'pay_time':$c_time,
			            	'utility_time'$cdtime:
			            	
			          
			            }", 0);
			            //发送到 xxx3809293670ctr的主题 一个信息 内容为 setr=3xxxxxxxxx Qos 为 0
			            $mqtt->close();    //发送后关闭链接
			        }
                	//购买承租人
                	$id = $order['user_id'];
                	//购买的用户
                	$user = model('user')->where('id','=',$id)->find()->toArray();
                	if($user['parent_id'] > 0){
                		//上级用户id
                		$puser = model('user')->where('id','=',$user['parent_id'])->find()->toArray();
                		//上级用户拥有承租人身份的所有下级
                		$all = model('user')->where([
                			['parent_id','=',$puser['id']],
                			['zls','=',1]
                			])->select()->toArray();
                		$all = count($all);
                		if($all >= 10){
                			$iszls = 1;
                			model('user')->save(['zls'=>1,'is_zls'=>1],['id'=>$order['user_id']]);
                		}
                	}
                	model('order')->save(['status'=>40],['id'=>$order['id']]);
                	if(!isset($iszls))
                	{
                		model('user')->save(['zls'=>1],['id'=>$order['user_id']]);
                	}
                	$num = 10000;
					model('integral')->save(['source'=>17,'user_id'=>$id,'status'=>1,'num'=>$num]);
					$integralid = model('integral')->id;
					//代理商、承租人、服务中心的权益积分，均会被分为：（60%股票）（20%兑换产品）（6%税收）（14%无息贷款额度）
					$all = [];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>7,'num'=>$num*0.6,'class'=>1];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>1,'num'=>$num*0.2,'class'=>1];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>6,'num'=>$num*0.06,'class'=>1];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>3,'num'=>$num*0.14,'class'=>1];
					model('integraldetailed')->saveAll($all);
                }
            }
        }
        echo $payModel->notifyResult();
    }
    //订单状态变更，已付款
    public function status()
    {
        if($this->request->isPost())
        {
            $post = post();
            if(!isset($post['user_id'])) return fh(200,'error','缺少用户id',[]);
            if(!isset($post['id'])) return fh(200,'error','缺少订单id',[]);
            //当前订单数据
            $pd = ysh_select($this->request->controller(),['where'=>[['id','=',$post['id']],['user_id','=',$post['user_id']]]],2);
            if(!$pd) return fh('500','error','虚假数据',[]);
            //修改充电宝数据
            ysh_upload('battery',['id'=>$pd['list']['battery_id'],'user_id'=>0,'status'=>2]);
            $time = time();
            //计算金额
            $nowtime = $time - $pd['list']['create_time'];
            $nowtime = $nowtime/60/60;
            $money = $nowtime * 20;
            //进行结算，对各层级返利
            //当前订单，支付金额
            $order = model($this->request->controller())->where('id','=',$post['id'])->find()->toArray();
            $this->jiesuan($pd['list'],$money,$post['user_id'],$order);
            //更新订单数据
            $upload = ysh_upload($this->request->controller(),['id'=>$post['id'],'status'=>2,'update_time'=>$time,'money'=>$money]);
            if($upload){
                return fh(200,'success','修改成功',$upload);
            }else{
                return fh(200,'error','修改失败,数据存在问题',$upload);
            }
        }
    }
    //结算
    //当前订单，支付金额
    public function jiesuan($list,$money,$userid,$order)
    {
    	//使用的充电宝
    	$battery = $list['battery_id'];
    	$battery = model('battery')->get($battery)->toArray();
    	//机台信息
    	$batteryba = model('batteryba')->get($battery['batteryba_id'])->toArray();
    	//选择的商家
    	$business = $list['business_id'];
    	$business = model('business')->get($business)->toArray();
    	//承租人信息
    	$czr = model('user')->get($business['pid'])->toArray();
    	
		
    	
    	//设备管理员5%
    	if($batteryba['pid'] > 0){
    		$sbglmoney = $money*0.05;
    		//钱包最新数据
			$qb = model('wallet')->where('user_id','=',$batteryba['pid'])->order('id','desc')->find();
			if(!empty($qb)){
				$qb = $qb->toArray();
				$xianmoney = $qb['balance'];
			}else{
				$xianmoney = 0;
			}
			//钱包添加余额
			model('wallet')->isUpdate(false)->data([
				'user_id'=>$batteryba['pid'],
				'status'=>1,
				'class'=>8,
				'money'=>$sbglmoney,
				'balance'=>$xianmoney+$sbglmoney,
				'orderid'=>$order['orderid']
				],true)->save();
    	}
    	//商家10%
    	$sjmoney = $money*0.1;
    	//钱包添加余额
		model('wallet')->isUpdate(false)->data([
			'user_id'=>$business['id'],
			'status'=>1,
			'class'=>7,
			'money'=>$sjmoney,
			'balance'=>$xianmoney+$sjmoney,
			'orderid'=>$order['orderid']
			],true)->save();
    	//钱包最新数据
		$qb = model('wallet')->where('user_id','=',$business['id'])->order('id','desc')->find();
		if(!empty($qb)){
			$qb = $qb->toArray();
			$xianmoney = $qb['balance'];
		}else{
			$xianmoney = 0;
		}
    	//承租人30%
    	$czrmoney = $money*0.3;
    	//钱包最新数据
		$qb = model('wallet')->where('user_id','=',$czr['id'])->order('id','desc')->find();
		if(!empty($qb)){
			$qb = $qb->toArray();
			$xianmoney = $qb['balance'];
		}else{
			$xianmoney = 0;
		}
		//钱包添加余额
		model('wallet')->isUpdate(false)->data([
			'user_id'=>$czr['id'],
			'status'=>1,
			'class'=>6,
			'money'=>$czrmoney,
			'balance'=>$xianmoney+$czrmoney,
			'orderid'=>$order['orderid']
			],true)->save();
    	//剩余的55%（化为100%再进行上级分成）
    	$newmoney = $money*0.55;
    	//承租人上级5%
    	if($czr['parent_id'] > 0){
			$pids = $newmoney*0.05;
    		if($czr['is_zls'] == 2){
				$czrsj = model('user')->get($czr['parent_id'])->toArray();
				$pids = $newmoney*0.05;
				//钱包最新数据
    			$qb = model('wallet')->where('user_id','=',$czrsj['id'])->order('id','desc')->find();
    			if(!empty($qb)){
    				$qb = $qb->toArray();
    				$xianmoney = $qb['balance'];
    			}else{
    				$xianmoney = 0;
    			}
    			//上级用户拥有的承租人大于10，收益数据返给平台
    			model('assets')->isUpdate(false)->data([
				'money'=>$ptje,
				'moneyclass'=>1,
				'relation'=>3,
				'class'=>5,
				'user_id'=>$userid,
				'orderid'=>$order['orderid']
				],true)->save();
    		}
    	}
    	//服务中心30%
    	//承租人绑定了服务中心
    	if($czr['fwgl_id'] > 0){
    		$fwmoney = $newmoney*0.3;
    		//钱包最新数据
			$qb = model('wallet')->where('user_id','=',$czr['id'])->order('id','desc')->find();
			if(!empty($qb)){
				$qb = $qb->toArray();
				$xianmoney = $qb['balance'];
			}else{
				$xianmoney = 0;
			}
			//钱包添加余额
			model('wallet')->isUpdate(false)->data([
				'user_id'=>$czr['id'],
				'status'=>1,
				'class'=>4,
				'money'=>$fwmoney,
				'balance'=>$xianmoney+$fwmoney,
				'orderid'=>$order['orderid']
				],true)->save();
    	}
    	//管理中心10%
    	//承租人绑定了管理中心
    	if($czr['glzx_id'] > 0){
    		$glmoney = $newmoney*0.1;
    		//钱包最新数据
			$qb = model('wallet')->where('user_id','=',$czr['id'])->order('id','desc')->find();
			if(!empty($qb)){
				$qb = $qb->toArray();
				$xianmoney = $qb['balance'];
			}else{
				$xianmoney = 0;
			}
			//钱包添加余额
			model('wallet')->isUpdate(false)->data([
				'user_id'=>$czr['id'],
				'status'=>1,
				'class'=>5,
				'money'=>$glmoney,
				'balance'=>$xianmoney+$glmoney,
				'orderid'=>$order['orderid']
				],true)->save();
    	}
    	//如果没有对应的上级身份，归平台所有
    	$pidsq = $pidsq ?? 0;
    	$pidss = $pidss ?? 0;
    	$pidssh = $pidssh ?? 0;
    	$fwmoney = $fwmoney ?? 0;
    	$glmoney = $glmoney ?? 0;
    	//分出去的金额
    	$hj = $pidsq+$pidss+$pidssh+$fwmoney+$glmoney;
    	//55%中没分出去的金额，全部归平台所有
    	//平台所得
    	$ptje = $newmoney - $hj;
    	if($ptje > 0){
    		model('assets')->isUpdate(false)->data([
				'money'=>$ptje,
				'moneyclass'=>1,
				'relation'=>3,
				'class'=>4,
				'user_id'=>$userid,
				'orderid'=>$order['orderid']
				],true)->save();
    	}
    	
    }
    
    //订单详情
    public function view()
    {
    	if($this->request->isPost())
    	{
    		$post = post();
    		if(!isset($post['id'])) return fh(200,'error','缺少订单参数',[]);
    		if(!isset($post['user_id'])) return fh(200,'error','缺少用户数据',[]);
    		$order = model($this->request->controller())->with('battery.batteryba.business')->where([['id','=',$post['id']],['user_id','=',$post['user_id']]])->find();
    		if(!empty($order)){
    			$order = $order->toArray();
    			return fh(200,'success','',$order);
    		}else{
    			return fh(200,'error','没有订单数据',[]);
    		}
    	}
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
